// pages/xq_blue/xq_send_file/xq_send_file.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deviceId: "",
    service: null,
    infoCharacteristic: null,
    dataCharacteristic: null,
    sendByte: 230
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("加载")
    console.log(options)

    var self = this
    self.setData({
      deviceId: options.deviceId
    })

    self.xq_onBLEConnectionStateChange()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.xq_getServicesAndCharacteristics()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("页面结束")

    var deviceId = this.data.deviceId
    console.log(deviceId)

    wx.onBLEConnectionStateChange(function(res){
      
    })

    wx.closeBLEConnection({
      deviceId: deviceId,
      success: function(res) {
        console.log("断开连接")
        console.log(res)
      },
    })
  },


  // 监听蓝牙连接状态
  xq_onBLEConnectionStateChange: function() {
    let self = this
    wx.onBLEConnectionStateChange(function(res){

      if (self.data.deviceId == res.deviceId && !res.connected) {
        console.log("已断开连接")
        wx.navigateBack({
          
        })
      }

    })
  },


  // 获取服务和特性
  xq_getServicesAndCharacteristics: function() {
    let self = this
    var deviceId = this.data.deviceId

    // 清除原来数据
    this.setData({
      service: null,
      infoCharacteristic: null,
      dataCharacteristic: null,
    })

    wx.showLoading({
      title: '获取服务中',
    })

    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function(res) {
        console.log("获取服务成功")
        console.log(res)


        // { isPrimary: true, uuid: "0000180A-0000-1000-8000-00805F9B34FB" }

        for (var i = 0; i < res.services.length; i++) {
          var service = res.services[i]
          if (service.uuid == "CCCC3936-AA0D-4873-9405-AACBACAE64B9") {
            self.setData({
              service: service,
            })
            self.xq_getCharacteristics(deviceId, service.uuid)
            break
          }

        }

      },
    })

  },

  // 获取特性
  xq_getCharacteristics: function(deviceId, serviceId) {
    console.log(deviceId + serviceId)
    let self = this
    var servers = this.data.services

    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function(res) {

        // properties : { notify: false, write: false, indicate: false, read: true }
        // uuid : "00002A29-0000-1000-8000-00805F9B34FB"

        for (var i = 0; i < res.characteristics.length; i++) {
          if (res.characteristics[i].uuid == "1DCBC186-DD15-49A4-8D37-2537BEE42EA2") {
            self.setData({
              infoCharacteristic: res.characteristics[i],
            })
          } else if (res.characteristics[i].uuid == "B82D215F-2DB7-44D0-899E-5EC4333E335E") {
            self.setData({
              dataCharacteristic: res.characteristics[i],
            })
          }
        }

        console.log("获取特性成功")
        console.log(res)

        wx.hideLoading()

      },
    })

  },


  // 点击特征值
  xq_tapCharacteristics: function() {
    if (this.data.service == null) {
      wx.showToast({
        title: '不存在服务',
        icon: 'none'
      })
      return
    }

    if (this.data.infoCharacteristic == null || this.data.dataCharacteristic == null) {
      wx.showToast({
        title: '不存在特征',
        icon: 'none'
      })
      return
    }

    var self = this

    wx.showActionSheet({
      itemList: ["发送图片", "发送视频"],
      success: function(res) {

        if (res.tapIndex == 0) {
          self.xq_selectImage()
        } else if (res.tapIndex == 1) {
          self.xq_selectVideo()
        }

      }
    })

  },


  // 选择视频
  xq_selectVideo: function() {
    var self = this
    // 这里选择的视频， 是wx压缩过得
    wx.chooseVideo({
      sourceType: ["album"],
      success: function(res) {
        /**
         * duration: 1 秒
         * height: 高
         * width: 宽
         * size: 大小
         * tempFilePath: 文件地址
         */
        console.log("获取数据成功")
        console.log(res)

        self.xq_sendAck(res.tempFilePath, res.size, 0)
      },
    })
  },


  // 选择图片
  xq_selectImage: function() {
    let self = this
    wx.chooseImage({
      count: 1,
      sourceType: ["album"],
      success: function(res) {
        console.log("获取数据成功")
        console.log(res)
        // tempFilePaths: 只有字符串路径
        // tempFiles: 路径 and 文件大小 {path: "wxfile://tmp_e818978347374f9f45a142bb345d0f94.jpg", size: 107950}
        // { errMsg: "chooseImage:ok", tempFilePaths: Array(1), tempFiles: Array(1) }
        self.xq_sendAck(res.tempFiles[0].path, res.tempFiles[0].size, 1)
      },
    })
  },


  // 发送询问
  xq_sendAck: function(tempFilePath, size, fileType) {
    // 现在超过10M的， 都不给发
    if (size > 9999999) {
      wx.showToast({
        title: '文件过大',
        icon: 'none'
      })
      return
    }

    let self = this

    console.log(tempFilePath, size, fileType)

    let length = 7
    let nBufferArray = new ArrayBuffer(length)
    let dataView = new DataView(nBufferArray)
    // 协议版本
    dataView.setUint8(0, 0)

    // 文件类型
    dataView.setUint8(1, fileType)

    // 文件大小
    let sizeStr = size.toString(16)
    // 补0
    for (var i = 8 - sizeStr.length - 1; i >= 0; i--) {
      sizeStr = "0" + sizeStr;
    }

    dataView.setUint8(2, parseInt(sizeStr.substring(0, 2), 16))
    dataView.setUint8(3, parseInt(sizeStr.substring(2, 4), 16))
    dataView.setUint8(4, parseInt(sizeStr.substring(4, 6), 16))
    dataView.setUint8(5, parseInt(sizeStr.substring(6, 8), 16))

    // tag
    // let tag = self.xq_timest()
    let tag = 1
    dataView.setUint8(6, tag)

    console.log("发送确认码")
    wx.showToast({
      title: '正在发送确认',
      icon: 'none'
    })

    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.service.uuid,
      characteristicId: this.data.infoCharacteristic.uuid,
      value: nBufferArray,
      success: function(res) {

        wx.showToast({
          title: '开始发送数据',
          icon: 'none'
        })

        console.log("发送确认码成功")
        console.log(res)
        self.xq_sendData(tempFilePath, tag, self.data.sendByte)

      },
    })
  },


  // 获取时间戳
  xq_timest: function() {
    var tmp = Date.parse(new Date()).toString()
    tmp = tmp.substr(0, 10)
    return tmp
  },


  /** 发送数据
   * 
   * @param tempFilePath 文件路径
   * @param tag 文件tag
   * @param length 每次发送数据大小
   */
  xq_sendData: function(tempFilePath, tag, length) {
    let self = this
    let deviceId = this.data.deviceId
    let serverId = this.data.service.uuid
    let characteristicsUUID = this.data.dataCharacteristic.uuid

    console.log("各种id", deviceId, characteristicsUUID, serverId)

    var file = wx.getFileSystemManager()
    file.readFile({
      filePath: tempFilePath,
      success: function(res) {

        // {errMsg: "readFile:ok", data: ArrayBuffer}

        console.log("获取文件数据成功")
        console.log(res)

        var buffer = res.data

        // 切割数据发送

        // 每次要发送数据的大小
        // let length = 230

        // 发送次数
        var count = buffer.byteLength / length

        // 当前文件 dataView
        let totalDataView = new DataView(buffer)

        // 切割余数长度
        let remainder = count % 1
        count -= remainder

        console.log("开始切割: ", res.data.byteLength, buffer.byteLength, count, length, remainder)

        // 头帧长度
        let initInt = 1

        // 开始发送
        self.xq_for_send_file(totalDataView, tag, deviceId, serverId, characteristicsUUID, initInt, buffer.byteLength, length, count, remainder, 0)

      }

    })


  },


  /**
   * 递归自己发送数据
   * 
   * @param totalDataView 总数据
   * @param tag 发送的tag
   * @param deviceId 蓝牙id
   * @param serverId 服务id
   * @param characteristicsUUID 特征id
   * @param initInt 前面帧长度
   * @param dataLength 数据总大小
   * @param length 每次要发的数据长度
   * @param count 总循环次数(就是数据总长度/每次要发的数据长度)
   * @param remainder 余数, 就是循环发完之后，需不需要再次发一次不够 length 的长度
   * @param i 当前循环的次数
   */
  xq_for_send_file: function(totalDataView, tag, deviceId, serverId, characteristicsUUID, initInt, dataLength, length, count, remainder, i) {

    // 头帧 + 数据
    let nBufferArray = new ArrayBuffer(initInt + length)
    let dataView = new DataView(nBufferArray)


    // 添加tag
    if (remainder <= 0 && i == count - 1) {
      // 没有余数, 并且最后一个
      dataView.setInt8(0, tag + 10)
    } else {
      dataView.setInt8(0, tag)
    }

    // 添加数据
    let offset = i * length
    for (var j = 0; j < length; j++) {
      // 每次设置某一位的值, int8类型
      dataView.setInt8(1 + j, totalDataView.getInt8(offset + j))
    }

    // 发送数据
    let index = i
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serverId,
      characteristicId: characteristicsUUID,
      value: nBufferArray,
      success: function(res) {
        // { errCode: 0, errMsg: "writeBLECharacteristicValue:ok" }
        // console.log(res)
        if (remainder <= 0 && index >= count - 1) {
          wx.showActionSheet({
            itemList: ['发送结束'],
          })
        }

      },
    })


    i += 1
    if (i < count) {
      // 这里有个神奇的发现, 就是你如果for循环执行发送蓝牙的话, 那么就会出现延迟发送, 不知道是wx帮你做了延时, 还是系统自动帮你延时
      // 继续循环
      this.xq_for_send_file(totalDataView, tag, deviceId, serverId, characteristicsUUID, initInt, dataLength, length, count, remainder, i)
      // setTimeout(this.xq_for_send_file(totalDataView, tag, deviceId, serverId, characteristicsUUID, initInt, dataLength, length, count, remainder, i), 100)

    } else {
      // 跳出循环

      // 发出余数
      if (remainder > 0) {
        console.log('发出余数')

        let maxLength = count * length
        let endLength = dataLength - maxLength
        let nBufferArray = new ArrayBuffer(initInt + endLength)
        let dataView = new DataView(nBufferArray)

        // 设置tag
        dataView.setInt8(0, tag + 10)
        // 设置数据
        for (var j = 0; j < endLength; j++) {
          dataView.setInt8(1 + j, totalDataView.getInt8(maxLength + j))
        }

        wx.writeBLECharacteristicValue({
          deviceId: deviceId,
          serviceId: serverId,
          characteristicId: characteristicsUUID,
          value: nBufferArray,
          success: function(res) {
            wx.showActionSheet({
              itemList: ['发送结束'],
            })

          },
        })
      }

      console.log("结束切割")

    }

  },


  // 输入框的监听
  xq_inputContent: function(data) {
    let value = data.detail.value
    let valueInt = parseInt(value)

    if (valueInt <= 0) {
      this.setData({
        sendByte: 230
      })

    } else {
      this.setData({
        sendByte: valueInt
      })

    }
  },







  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})